package edu.xmu.software.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import edu.xmu.software.dao.UserInfoDAO;

public class LoginController extends AbstractController {

	private UserInfoDAO userInfoDAO;

	public void setUserInfoDAO(UserInfoDAO userInfoDAO) {
		this.userInfoDAO = userInfoDAO;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String userName = request.getParameter("Username");
		String password = request.getParameter("Password");
		boolean isAuth = userInfoDAO.isAuth(userName, password);
		Map<String, Object> retObject = new HashMap<String, Object>();
		retObject.put("isSuccess", isAuth);
		if (isAuth == true) {
			String redirect = (String) request.getSession().getAttribute("redirect");
			request.getSession().invalidate();
			request.getSession().setAttribute("userinfo", true);
			request.getSession().setAttribute("userName", userName);
			//return new ModelAndView("select");			
			System.out.println("wwwreto: "+redirect);
			if (redirect != null) {
				System.out.println("ddreto: "+redirect);
				response.sendRedirect(redirect);
			} else {
				response.sendRedirect("page.do?action=index");
			}
			return null;
		} else {
			// output.write(JSON.encode(retObject).getBytes());
			response.sendRedirect("userRedirect.do?action=login&error=1");
			return null;
		}
	}
}
